import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:froom_generator/processor/entity_processor.dart';
import 'package:source_gen/source_gen.dart';
import 'package:froom_annotation/froom_annotation.dart';
import 'package:froom_generator/value_object/type_converter.dart' as froom_gen;
import 'dart:async';

import 'package:fall_gen_base/fall_gen_base.dart';
import '../writer/entity_writer.dart';
import '../utils/tc_util.dart';

/// 实体增强代码生成器
/// 继承GeneratorForAnnotation，为@Entity注解的类生成part文件格式的增强代码
class EntityGenerator extends GeneratorForAnnotation<Entity> {
  final String typeConverterPath;
  const EntityGenerator(this.typeConverterPath);

  @override
  FutureOr<String> generateForAnnotatedElement(
    Element element,
    ConstantReader annotation,
    BuildStep buildStep,
  ) async {
    LogUtil.d('🔥 EntityGenerator: 开始处理 ${element.name}');

    // 确保element是ClassElement
    if (element is! ClassElement) {
      throw InvalidGenerationSourceError(
        'EntityGenerator只能应用于类，但发现应用于${element.runtimeType}',
        element: element,
      );
    }

    try {
      LogUtil.d('🔥 EntityGenerator: 开始加载TypeConverters for ${element.name}');

      // 动态加载TypeConverter
      final typeConverters = await _loadTypeConverters(buildStep);
      LogUtil.d(
          '🔥 EntityGenerator: 加载了 ${typeConverters.length} 个TypeConverters');

      // 使用froom_generator的EntityProcessor解析实体
      LogUtil.d('🔥 EntityGenerator: 开始处理实体 ${element.name}');
      final processor = EntityProcessor(element, typeConverters);
      final entity = processor.process();
      LogUtil.d('🔥 EntityGenerator: 实体处理完成，开始生成代码');

      // 使用EntityWriter生成part文件格式的代码
      final writer = EntityWriter(entity);
      final result = writer.generatePartFileCode();
      LogUtil.d('🔥 EntityGenerator: 代码生成完成 for ${element.name}');
      return result;
    } catch (e) {
      LogUtil.d('🔥 EntityGenerator: 生成失败 for ${element.name}: $e');
      throw InvalidGenerationSourceError(
        '为类${element.name}生成增强代码时出错: $e',
        element: element,
      );
    }
  }

  /// 动态加载TypeConverter类
  Future<Set<froom_gen.TypeConverter>> _loadTypeConverters(
      BuildStep buildStep) async {
    try {
      // 使用ClassUtil加载TypeConverter子类
      final typeConverterClasses = await TcUtil.loadTypeConverters(
        buildStep,
        typeConverterPath,
      );

      // 使用TcUtil转换为froom_gen.TypeConverter
      if (typeConverterClasses.isNotEmpty) {
        final convertedTypeConverters = TcUtil.getTypeConverters(
          typeConverterClasses,
          froom_gen.TypeConverterScope.database, // 默认作用域
        );
        LogUtil.d(
            '✅ _loadTypeConverters: 成功加载 ${convertedTypeConverters.length} 个TypeConverter');
        return convertedTypeConverters;
      }

      LogUtil.d('⚠️ _loadTypeConverters: 未在文件中找到任何TypeConverter类');
      return <froom_gen.TypeConverter>{};
    } catch (e) {
      LogUtil.d('⚠️ _loadTypeConverters: 加载TypeConverter时发生错误: $e');
      return <froom_gen.TypeConverter>{};
    }
  }
}
